﻿using System;
using System.Collections.Generic;
using System.Linq;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Domain.Commands;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsMediaFileSelectOneDataCommand : CmsMediaFileSelectOneCommand
    {
        public override CmsMediaFile ExecuteOne()
        {
            CmsMediaFile result = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsMediaFile>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsMediaFile>;

            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<CmsMediaFile, int>>();

                var data = SqlUtility<CmsMediaFile, int>.ExecuteReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_MediaFileSelectOne",
                        new
                        {
                            SiteId = CommandParameter.SiteId,
                            SiteGroupId = CommandParameter.SiteGroupId,
                            MediaFileId = CommandParameter.Id
                        },
                        mapper);

                result = data != null ?
                    data.FirstOrDefault() :
                    null;
            }

            return result;
        }
    }
}
